<template>
   <view class="submitHomework">
	   <view class="page-title">作业信息</view>
	   <view class="form-wrapper">
		   <u-form :model="form" ref="uForm" label-width="140rpx">
			 <u-form-item label="图片素材">
			   <!--    <u-upload ref="uUpload" :custom-btn="true" v-model="imgUrl" :limitType="['png', 'jpg', 'jpeg', 'webp', 'gif']" :auto-upload="false" @on-choose-complete="uploadChooseImage" :before-upload="beforeUpload">
			   		<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
			   				<u-icon name="photo" size="60" :color="$u.color['lightColor']"></u-icon>
			   			</view>
			   	</u-upload> -->
			   	<uni-file-picker ref="files2" v-model="imgUrl"  file-mediatype="image" file-extname="png,jpg,jpeg,webp,gif" title="" :auto-upload="false" :list-styles="listStyles"
			   	@select="uploadChooseImage"
			   	@delete="hanleDelete3"></uni-file-picker>
			 </u-form-item>
		     <u-form-item label="附件">
			   <!-- #ifdef MP-WEIXIN|| H5  -->
			   <uni-file-picker ref="files" v-model="attachmentUrl"  file-mediatype="all" title="" :auto-upload="false" :list-styles="listStyles"
				@select="select" 
				@progress="progress" 
				@success="success" 
				@fail="fail" 
				@delete="hanleDelete"></uni-file-picker>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS  -->
				<file-choose @change-file="changeFile" :showFileList="true" :config="file_config" @input="hanleDelete2"></file-choose>
<!-- 					<view v-for="(item, index) in attachmentList" :key="index" style="display: flex;justify-content: space-between;">
					<text>{{item.name}}</text> <u-icon name="close" @click="hanleDelete2(item,index)"></u-icon>
				</view> -->
				<!-- #endif -->
		    </u-form-item>
		   	<u-form-item label="内容" prop="intro">
				<!-- <u-input v-model="form.intro" placeholder="请输入内容"/> -->
				<uni-easyinput type="textarea" autoHeight v-model="form.intro" placeholder="请输入内容"></uni-easyinput>
			</u-form-item>
		   </u-form>
	   </view>
	   <!-- 操作按钮 -->
	   <view class="footer">
	     <view class="btn-wrapper">
	       <view class="btn-item btn-item-main" :class="{ disabled }" @click="handleSubmit()">保存</view>
	     </view>
	   </view>
   </view>
</template>

<script>
  import {
	 uploadFile, getCommonToken, uploadFile2
  } from '@/utils/upload.js' //引入方法
  import * as FindApi from '@/api/find'
  import * as homeworkApi from '@/api/homework'
  import FileChoose from '@/uni_modules/file-choose/components/file-choose/file-choose.vue'
  // 表单验证规则
  const rules = {
    nickName: [{
      required: true,
      message: '请输入用户昵称',
      trigger: ['blur', 'change']
    }],
  }
  export default {
	  components:{
		  FileChoose
	  },
    data() {
      return {
		// 按钮禁用
		disabled: false,
		// 文件路径 (用于显示)
		attachmentUrl: [],
		imgUrl: [], 
		// 临时文件 (用于上传)
		tempFile: null,
		// 表单数据
		form: {
		  attachment: [],
		  img: [],
		  intro: '', //简介
		},
		// 临时图片 (用于上传)
		tempFile2: null,
		// 验证规则
		rules,
		listStyles:{
			// 是否显示边框
			border: false,
			// 是否显示分隔线
			dividline: true,
			// 线条样式
			borderStyle: {
				width:1,
				color:'blue',
				radius:2
			},
			id: null
		},
		file_config: {
			size: 50,
			limit: 10,
			title: "",
			headers: {},
			formData: {},
			automatic: false, //是否自动上传
			fileMediatype: "file"
		},
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		this.id = options.id
        // this.getCommonStsToken()
    },
    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
      this.$refs.uForm.setRules(this.rules)
    },
    methods: {
		// 获取上传临时密钥
		getCommonStsToken() {
			FindApi.commonToken({})
			  .then(result => {
				getCommonToken(result)
			  })
		},
		// 获取上传状态
		async select(e){
			const app = this
			console.log('选择文件：',e)
			app.tempFile = e.tempFiles[0]
			app.attachmentUrl.push(app.tempFile.path)
			// 先上传头像图片
			if (app.tempFile && !await app.uploadFileFun()) {
			  app.$toast('很抱歉，文件上传失败')
			  return
			}
		},
		// 获取上传进度
		progress(e){
			console.log('上传进度：',e)
		},
		
		// 上传成功
		success(e){
			console.log('上传成功')
		},
		
		// 上传失败
		fail(e){
			console.log('上传失败：',e)
		},
		hanleDelete(e){
			console.log('删除：',e)
			this.attachmentUrl.splice(e.index,1)
			this.form.attachment.splice(e.index,1)
			console.log(this.attachmentUrl)
		},
		// 选择图片
		async uploadChooseImage(e) {
		  const app = this
		  console.log('选择文件：',e)
		  app.tempFile2 = e.tempFiles[0]
		  app.imgUrl.push({
				url: app.tempFile2.path,
				extname: app.tempFile2.extname,
				name: app.tempFile2.name
			})
		  // this.$refs.uUpload.upload();
		  // 选择图片
		 if (app.tempFile2 && !await app.uploadImgFun()) {
		   app.$toast('很抱歉，图片上传失败')
		   return
		 }
		},
		hanleDelete3(val) {
			console.log('删除：',val)
			this.imgUrl.splice(val.index,1)
			this.form.img.splice(val.index,1)
			console.log(this.imgUrl)
		},
		// 上传图片
		uploadImgFun() {
		    const app = this
			//#ifdef MP-WEIXIN
			let startIndex = app.tempFile2.path.indexOf('.')
			let urls = app.tempFile2.path.substring(startIndex);
			//#endif
			//#ifdef H5
			let startIndex = app.tempFile2.name.lastIndexOf('.')
			let urls = app.tempFile2.name.substring(startIndex);
			//#endif
			const [y, m, d] = [new Date().getFullYear(), String(new Date().getMonth() + 1).padStart(2, '0'), String(new Date().getDate()).padStart(2, '0')];
			const fileName = `images/console/${y}${m}${d}/${Date.now()}_${Math.random().toString(36).substr(2, 6)}${urls}`; // 生成文件名
			console.log(app.tempFile2,fileName, urls)
			return FindApi.commonToken({})
			  .then(result => {
			    //#ifdef MP-WEIXIN || APP-PLUS
				return uploadFile(result, app.tempFile2.path,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.img.push(url_l)
						app.tempFile2 = null
						// app.$refs.files2.upload()
						app.$toast('上传成功')
						return true
					}
				}).catch(() => {
				  return false
				})
				//#endif
				//#ifdef H5
				return uploadFile2(result, app.tempFile2.file,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.img.push(url_l)
						app.tempFile2 = null
						app.$refs.files2.upload()
						app.$toast('上传成功')
						return true
					}
				}).catch(() => {
				   return false
				 })
				//#endif
			  })
		},
		// 上传附件
		uploadFileFun() {
		    const app = this
			//#ifdef MP-WEIXIN
			let startIndex = app.tempFile.path.indexOf('.')
			let urls = app.tempFile.path.substring(startIndex);
			//#endif
			//#ifdef H5
			let startIndex = app.tempFile.name.lastIndexOf('.')
			let urls = app.tempFile.name.substring(startIndex);
			//#endif
			const [y, m, d] = [new Date().getFullYear(), String(new Date().getMonth() + 1).padStart(2, '0'), String(new Date().getDate()).padStart(2, '0')];
			const fileName = `images/console/${y}${m}${d}/${Date.now()}_${Math.random().toString(36).substr(2, 6)}${urls}`; // 生成文件名
			console.log(app.tempFile,fileName, urls)
			return FindApi.commonToken({})
			  .then(result => {
			    //#ifdef MP-WEIXIN
				return uploadFile(result, app.tempFile.path,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.attachment.push(url_l)
						app.tempFile = null
						app.$refs.files.upload()
						app.$toast('上传成功')
						return true
					}
				}).catch(() => {
				  return false
				})
				//#endif
				//#ifdef H5
				return uploadFile2(result, app.tempFile.file,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.attachment.push(url_l)
						app.tempFile = null
						app.$refs.files.upload()
						app.$toast('上传成功')
						return true
					}
				}).catch(() => {
				   return false
				 })
				//#endif
			  })
		},
		// app上传
		async changeFile(file) {
			console.log('选择文件',file,file[0])
			let path = file[0].url
			const app = this
			app.tempFile = path
			app.attachmentUrl.push(path)
			// 先上传头像图片
			if (app.tempFile && !await app.uploadFileFun2()) {
			  app.$toast('很抱歉，文件上传失败')
			  return
			}
		 },
        // app上传文件
		uploadFileFun2() {
		     const app = this
		 	let startIndex = app.tempFile.lastIndexOf('.')
		 	let urls = app.tempFile.substring(startIndex);
			const [y, m, d] = [new Date().getFullYear(), String(new Date().getMonth() + 1).padStart(2, '0'), String(new Date().getDate()).padStart(2, '0')];
		 	const fileName = `images/console/${y}${m}${d}/${Date.now()}_${Math.random().toString(36).substr(2, 6)}${urls}`; // 生成文件名
		 	console.log(app.tempFile,fileName, urls)
			return FindApi.commonToken({})
			  .then(result => {
				return uploadFile(result, app.tempFile,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.attachment.push(url_l)
						app.tempFile = null
						app.$toast('上传成功')
						return true
					}
				}).catch(() => {
				  return false
				})
			  })
		},
		hanleDelete2(val){
			console.log('删除：',val)
			this.attachmentUrl.splice(val.index,1)
			this.form.attachment.splice(val.index,1)
			console.log(this.attachmentUrl)
		},
      // 确认修改
      async handleSubmit() {
        const app = this
        // 判断是否重复提交
        if (app.disabled === true) return
        app.$refs.uForm.validate(async valid => {
          if (!valid) return
          // 按钮禁用
          app.disabled = true
          // // 先上传头像图片
          // if (app.tempFile && !await app.uploadFileFun()) {
          //   app.$toast('很抱歉，文件上传失败')
          //   app.disabled = false
          //   return
          // }
		  let attachment = [app.form.img, app.form.attachment]
		  let obj = {
		    id: app.id,
		    content: app.form.intro,
		    attachment: attachment ? JSON.stringify(attachment) : ''
		  }
		  console.log('提交内容', app.form,obj)
          // 提交保存个人信息
          homeworkApi.homeworkSubmit(obj)
            .then(result => {
              app.$toast(result.message)
              setTimeout(() => {
                app.disabled = false
				app.onNavigateBack(1)
              }, 1500)
            })
            .catch(err => app.disabled = false)
        })
      },
	  
	  /**
	   * 提交成功-跳转回原页面刷新数据
	   */
	  onNavigateBack(delta = 1) {
	    const pages = getCurrentPages()
		const prevPage = pages[pages.length - 2]; // 上一页实例
	    if (pages.length > 1) {
	      uni.navigateBack({
	        delta: Number(delta || 1),
			success: function() {
				prevPage.$vm.refreshData(); // 执行前一个页面的刷新
			}
	      })
	    } else {
	      this.$navTo('pages/index/index')
	    }
	  }
    }
  }
</script>

<style lang="scss" scoped>
	page {
	  background: #f7f8fa;
	}
 .submitHomework{ 
	 .page-title {
	   width: 94%;
	   margin: 0 auto;
	   padding-top: 40rpx;
	   font-size: 28rpx;
	   color: rgba(69, 90, 100, 0.6);
	 }
	 
	 .form-wrapper {
	   margin: 20rpx auto 20rpx auto;
	   padding: 0 40rpx;
	   width: 94%;
	   box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
	   border-radius: 16rpx;
	   background: #fff;
	 }
	 /* 底部操作栏 */
	 
	 .footer {
	   margin-top: 80rpx;
	 
	   .btn-wrapper {
	     height: 100%;
	     // display: flex;
	     // align-items: center;
	     padding: 0 20rpx;
	   }
	 
	   .btn-item {
	     flex: 1;
	     font-size: 28rpx;
	     height: 86rpx;
	     color: #fff;
	     border-radius: 50rpx;
	     display: flex;
	     justify-content: center;
	     align-items: center;
	   }
	 
	   .btn-item-main {
	     background: linear-gradient(to right, #29ad68, #29ad68);
	     color: #fff;
	 
	     // 禁用按钮
	     &.disabled {
	       opacity: 0.6;
	     }
	   }
	 
	 }
 }
</style>
